let path = require('path');
const fs = require('fs');

/**
* @description 读取文件夹下面的文件夹名称
* @param path 文件夹路径 string
* @returns 返回一个promise对象，resolve返回文件夹名称数组
*/
const readdir = (path) => {
  return new Promise((resolve, reject) => {
    fs.readdir(path, { withFileTypes: true }, (err, files) => {
      if (err) {
        reject(err);
      }
      const folderNames = files.filter(file => file.isDirectory()).map(folder => folder.name);
      return resolve(folderNames);
    })
  })
}

/**
* @description 同步读取文件内容
* @param path 文件路径 string
* @returns 返回文件内容 string
*/
const readFile = (path) => {
  return fs.readFileSync(path, (err, data) => {
    if (err) {
      return '';
    }
    return data;
  })
}

/** 路由文件地址*/
let routerPath = path.join(__dirname, 'src', 'router', 'index.js');
// 读取文件内容
fs.readFile(routerPath, 'utf-8', (err, data) => {
  if (err) {
    console.error('读取文件时出错:', err);
    return;
  }
  let startInd = data.indexOf('childrenList');
  //从开始下标开始寻找
  let resultStartInd = data.indexOf('[', startInd);
  let resultEndInd = data.indexOf(']', startInd);
  /** 需要替换的str*/
  let replaceStr = data.substring(resultStartInd, resultEndInd + 1);
  /** 原本文件中的路由列表*/
  let originalList = replaceStr
  originalList = originalList.replace(/\</g, '"<')
  originalList = originalList.replace(/\/\>/g, '/>"')
  originalList = JSON.parse(originalList);

  /** 是否需要更新路由*/
  let isChange = false;
  /** 替换的路由列表*/
  let replacingContent = [];

  readdir(path.join(__dirname, 'src', 'pages')).then(res => {
    let content = {}
    res.forEach((name) => {
      content = {};
      try {
        let filePath = path.join(__dirname, 'src', 'pages', name, 'pageConfig.ts')
        let fileData = readFile(filePath).toString();
        let startInd = fileData.indexOf('{')
        let endInd = fileData.lastIndexOf('}');
        let resultData = fileData.substring(startInd, endInd + 1);

        //正则去除空白符
        resultData = resultData.replace(/\s/g, '')
        //正则 ' 变为 "
        resultData = resultData.replace(/\'/g, '"')
        //正则去掉}前面的,
        resultData = resultData.replace(/\,(?=\})/g, '')
        //为key加上双引号
        resultData = resultData.replace(/([a-zA-Z0-9]+?):/g, '"$1":');

        resultData = JSON.parse((resultData))
        content = {
          ...resultData,
          path: `${name}`,
          sortInd: `${resultData.sortInd ? resultData.sortInd : res.length}`,
          element: `<${name.charAt(0).toUpperCase() + name.slice(1)} />`,
        }
        replacingContent.push(content);
      } catch (error) {
        content = {
          path: `${name}`,
          sortInd: `${res.length}`,
          element: `<${name.charAt(0).toUpperCase() + name.slice(1)} />`,
        }
        replacingContent.push(content);
      }
    })
    return res
  }).then((res) => {

    // 按照sortInd,从小到大排序
    replacingContent = replacingContent.sort((a, b) => {
      return a.sortInd - b.sortInd
    })

    if (replacingContent.length !== originalList.length) {
      isChange = true;
    }

    if (!isChange) {
      for (let i = 0; i < replacingContent.length; i++) {
        let keys = Object.keys(replacingContent[i]);
        /** 需要检查的key列表*/
        let checkKeys = keys.filter((item) => {
          return !['element', 'path'].includes(item)
        })
        /** 检查长度是否一样*/
        if (keys.length != Object.keys(originalList[i]).length) {
          isChange = true;
          break;
        }

        /** 检查key对相应的value是否一致*/
        for (let j = 0; j < keys.length; j++) {
          if (checkKeys.includes(keys[j]) && replacingContent[i][keys[j]] != originalList[i][keys[j]]) {
            isChange = true;
            break;
          }
        }
      }
    }

    if (isChange) {

      // 替换文件内容
      let updatedContent = data.replace(replaceStr, JSON.stringify(
        replacingContent
      ));
      //去除导入的组件,同时去掉回车符
      updatedContent = updatedContent.replace(/import.*from.*@.*\S/g, ' ')
      updatedContent = updatedContent.trim();

      // import 导入组件
      res.forEach((name) => {
        updatedContent = `import ${name.charAt(0).toUpperCase() + name.slice(1)} from '@/pages/${name}/index.tsx'\n`.concat(updatedContent)
      })

      updatedContent = updatedContent.replace(/\"\</g, '<')
      updatedContent = updatedContent.replace(/\>\"/g, '>')

      // 将更新后的内容写入文件
      fs.writeFile(routerPath, updatedContent, 'utf-8', (err) => {
        if (err) {
          console.error('写入文件时出错:', err);
          return;
        }
        console.log('文件内容已成功替换！');
      });
    }
  })
});
